SQL where clause
The select
statement will retrieve all the rows of the table.
If you need to retrieve the data based on some condition we will have to use the where
clause.
The where
clause is used to filter the records based on the condition provided.
Syntax
select column_1, column_2, ...
from table_name
where condition;
Let's assume that we have a table employee
with the following data.
empno | name | age | role | location |
---|---|---|---|---|
001 | Andrew | 30 | Manager | India |
002 | Beslin | 28 | Business Analyst | India |
003 | Joanna | 23 | Senior Developer | USA |
Example for where clause
select * from employee where location = 'India';
Output
empno | name | age | role | location |
---|---|---|---|---|
001 | Andrew | 30 | Manager | India |
002 | Beslin | 28 | Business Analyst | India |
We can perform multiple operation in where
clause.
Operation | Description |
---|---|
= | Equal |
> | Greater than |
< | Less than |
>= | Greater than or equal |
<= | Less than or equal |
<> | Not equal. |
BETWEEN | Between a certain range |
LIKE | Search for a pattern |
IN | To specify multiple possible values for a column |
Lets see few queries using the above operation.
Example 1
select * from employee where age > 25;
This will retrieve the employees whose age is greater than 25. The output will be as below.
empno | name | age | role | location |
---|---|---|---|---|
001 | Andrew | 30 | Manager | India |
002 | Beslin | 28 | Business Analyst | India |
Example 2
select * from employee where role <> 'Manager';
This will return the employees whose role is not Manager
.
Output
empno | name | age | role | location |
---|---|---|---|---|
002 | Beslin | 28 | Business Analyst | India |
003 | Joanna | 23 | Senior Developer | USA |
Example 3
select * from employee
WHERE age BETWEEN 21 AND 25;
This will return the records of the employee whose age is between 21 and 25.
Output
empno | name | age | role | location |
---|---|---|---|---|
003 | Joanna | 23 | Senior Developer | USA |
Example 4
select * from employee where name like '%lin%';
This will return the records of the employee whose name contains the pattern lin
in their name.
Output
empno | name | age | role | location |
---|---|---|---|---|
002 | Beslin | 28 | Business Analyst | India |
We can also use this like
query with following pattern.
'xx%' - Start's with xx.
'%x' - End's with x.
'%xx%' - Finds any value that contains xx pattern in it.
'x%' - Find the value that have x in the second position.
'x%' - Finds any values that start with x and are at least 2 characters in length.
'a%z' - Finds any values that start with a and ends with z.
Example 5
select * from employee where location in ('India','USA');
This will retrieve all the employees in India
and USA
location.
Output
empno | name | age | role | location |
---|---|---|---|---|
001 | Andrew | 30 | Manager | India |
002 | Beslin | 28 | Business Analyst | India |
003 | Joanna | 23 | Senior Developer | USA |